import { Store } from "../model/Store.js";

import { Op } from "sequelize";


//查询和搜索
const fn_list= async (ctx, next) => {
    //从请求的查询参数中获取关键字keyWord
    const keyword = ctx.request.query.keyword;
    
    //初始化查询条件
    let where = {};

    //如果关键字kewword真的存在，则设置查询条件
    if (keyword) {
        where = {
            [Op.or]: [
                { storeName: { [Op.like]: `%${keyword}%` } },//商品名称包含关键字
                { price: { [Op.like]: `%${keyword}%` } },//价格包含关键字
                { stock: { [Op.like]: `%${keyword}%` } }//库存包含关键字
            ]
        }
    }
    const stores = await Store.findAll({where});
    ctx.body = {
        code: 1000,
        msg: '获取商品成功',
        data: stores
    }
}

//商品信息
const fn_getById = async (ctx, next) => {
    //获取url的Id
    const id = ctx.params.id
    //查询数据库
    const store = await Store.findByPk(id)
    ctx.body = {
        code: 1000,
        msg: '获取数据成功！',
        data: store
    }
}

//添加商品
const fn_add = async (ctx, next) => {
    const store = ctx.request.body
    await Store.create(store)
    ctx.body = {
        code: 1000,
        msg: '添加商品成功！',
        data: null
    }
}
//修改商品
const fn_update = async (ctx, next) => {
    const id = ctx.params.id
    const store = ctx.request.body
    await Store.update(store, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '修改商品成功！',
        data: null
    }

}
//删除商品
const fn_delete = async (ctx, next) => {
    const id = ctx.params.id || 0

    await Store.destroy({
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 1000,
        msg: '删除商品成功！',
        data: null
    }
}

export default [
    {
        method: 'get',
        url: '/store',
        fn: fn_list
    },
    {
        method: 'get',
        url: '/store/:id',
        fn: fn_getById
    },
    {
        method: 'post',
        url: '/store',
        fn: fn_add
    },
    {
        method: 'put',
        url: '/store/:id',
        fn: fn_update
    },
    {
        method: 'delete',
        url: '/store/:id',
        fn: fn_delete
    }
]

